package me.edzh.spring.bootstrap.controller;

import lombok.extern.log4j.Log4j;
import me.edzh.spring.bootstrap.model.Response;
import me.edzh.spring.bootstrap.utils.JsonDateValueProcessor;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * Created by Edward on 2016/8/6.
 */

@Log4j
public class BaseController {

    public static void writeToClient(HttpServletResponse response, String result, String contentType) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-type", contentType);
            response.getWriter().write(result);
        } catch (IOException e) {
            log.error("write err", e);
        }
    }


    public static void writeToClient(HttpServletResponse response, String result) {

        writeToClient(response, result, "application/json;charset=UTF-8");
    }

    public static void writeToClient(HttpServletResponse response, JSONObject result) {

        if (null != result) {
            writeToClient(response, result.toString());
        }
    }

    public static void writeToClient(HttpServletResponse response, Response result) {

        if (null != result) {
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
            writeToClient(response, JSONObject.fromObject(result, jsonConfig).toString());
        }
    }

    public static void writeToClient(HttpServletResponse response, Object result) {
        if (null != result) {
            Response<Object> dto = new Response<>();
            dto.setData(result);
            writeToClient(response, dto);
        }
    }

    public static void writeToClient(HttpServletResponse response, boolean successed, Long ifErrorCode, String errorMessage) {
        if (successed)
            writeToClient(response, new Response());
        else
            writeToClient(response, new Response(ifErrorCode, errorMessage));
    }

}